package com.amarsoft.are;

import com.amarsoft.are.io.FileTool;
import com.amarsoft.are.lang.DataElement;
import com.amarsoft.are.lang.StringX;
import com.amarsoft.are.log.Log;
import com.amarsoft.are.log.LogFactory;
import com.amarsoft.are.metadata.DataSourceMetaData;
import com.amarsoft.are.metadata.MetaDataFactory;
import com.amarsoft.are.resource.AREResourceManager;
import com.amarsoft.are.sql.Connection;
import com.amarsoft.are.sql.DBConnectionFactory;
import com.amarsoft.are.util.conf.Attributes;
import com.amarsoft.are.util.conf.Configuration;
import com.amarsoft.are.util.conf.Node;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class ARE {
	public static final int RUN_MODE_STANDALONE = 0;
	public static final int RUN_MODE_WEBCONTAINER = 1;
	public static final int RUN_MODE_EJBCONTAINER = 3;
	private static int runMode = 0;
	private static Pattern varPattern = Pattern
			.compile("\\{\\$(?:(ARE)|(?:SYSTEM))\\.([^\\{\\}][^\\}]*)\\}");
	private static LinkedHashMap<String, AREServiceStub> services = new LinkedHashMap<String, AREServiceStub>();
	private static java.util.Properties systemProperties = new java.util.Properties();
	private static String version = "1.0b96";
	private static String configureFile = "etc/are.xml";
	private static boolean initialized = false;
	private static Log log = null;

	public static Connection getDBConnection(String paramString)
			throws SQLException {
		return DBConnectionFactory.getConnection(paramString);
	}

	public static DataSourceMetaData getMetaData(String paramString)
			throws SQLException {
		return MetaDataFactory.getMetaData(paramString);
	}

	public static Log getLog() {
		if (!(isInitOk()))
			return LogFactory.getLog("com.amarsoft.are.ARE");
		if (log == null)
			log = LogFactory.getLog("com.amarsoft.are.ARE");
		return log;
	}

	public static Log getLog(String paramString) {
		return LogFactory.getLog(paramString);
	}

	public static String getProperty(String paramString) {
		return systemProperties.getProperty(paramString);
	}

	public static void setProperty(String paramString1, String paramString2) {
		if (paramString2 != null)
			systemProperties.setProperty(paramString1,
					replaceARETags(paramString2));
		else
			systemProperties.setProperty(paramString1, paramString2);
	}

	public static void init() {
		String[] arrayOfString = { "are.xml", "etc/are.xml" };
		int i = 0;
		for (i = 0; i < arrayOfString.length; ++i) {
			File localFile = new File(arrayOfString[i]);
			if (localFile.exists())
				break;
		}
		if (i >= arrayOfString.length)
			return;
		init(arrayOfString[i]);
	}

	public static synchronized void init(String paramString) {
		if (initialized) {
			System.out
					.println(AREResourceManager.getResourceString("AREW0002"));
			return;
		}
		File localFile = FileTool.findFile(paramString);
		if (localFile == null) {
			System.out
					.println(new AREException(6, new String[] { "NULL FILE" })
							.getMessage());
			System.out
					.println(AREResourceManager.getResourceString("AREW0001"));
			System.out.println();
			return;
		}
		init(localFile);
	}

	public static synchronized void init(File paramFile) {
		if (initialized) {
			System.out
					.println(AREResourceManager.getResourceString("AREW0002"));
			return;
		}
		if (paramFile == null) {
			System.out
					.println(new AREException(6, new String[] { "NULL FILE" })
							.getMessage());
			System.out
					.println(AREResourceManager.getResourceString("AREW0001"));
			System.out.println();
			return;
		}
		try {
			init(new FileInputStream(paramFile));
		} catch (FileNotFoundException localFileNotFoundException) {
			System.out.println(new AREException(6, new String[] { paramFile
					.getAbsolutePath() }).getMessage());
			System.out
					.println(AREResourceManager.getResourceString("AREW0001"));
			System.out.println();
			localFileNotFoundException.printStackTrace(System.err);
		}
	}

	public static synchronized void init(InputStream paramInputStream) {
		if (initialized) {
			System.out
					.println(AREResourceManager.getResourceString("AREW0002"));
			return;
		}
		if (paramInputStream == null) {
			System.out.println(new AREException(6,
					new String[] { "NULL INPUT STREAM" }).getMessage());
			System.out
					.println(AREResourceManager.getResourceString("AREW0001"));
			System.out.println();
			return;
		}
		try {
			Configuration localConfiguration = new Configuration();
			localConfiguration.loadFromStream(paramInputStream);
			init(localConfiguration);
		} catch (Exception localException) {
			System.out.println(localException.getMessage());
			System.out
					.println(AREResourceManager.getResourceString("AREW0001"));
			System.out.println();
			localException.printStackTrace(System.err);
			return;
		}
	}

	private static synchronized void init(Configuration paramConfiguration) {
		System.out.println(AREResourceManager.getResourceString("AREI0001"));
		System.out.println();
		Node localNode = paramConfiguration.getRootNode();
		loadSystemProperties(localNode.getProperties());
		registerServices(localNode.getChild("AREServices"));
		initStartOnService();
		System.out.println();
		System.out.println(AREResourceManager.getResourceString("AREI0002"));
		System.out.println();
		initialized = true;
	}

	public static synchronized boolean isInitOk() {
		return initialized;
	}

	private static void loadSystemProperties(
			com.amarsoft.are.util.conf.Properties paramProperties) {
		System.out.println(AREResourceManager.getResourceString("AREI0003"));
		Iterator<?> localIterator = paramProperties.getProperties().iterator();
		while (localIterator.hasNext()) {
			DataElement localDataElement = (DataElement) localIterator.next();
			String str = localDataElement.getString();
			if (str != null)
				str = replaceARETags(str);
			systemProperties.put(localDataElement.getName(), str);
		}
		System.getProperties().putAll(systemProperties);
		System.out.println(AREResourceManager.getResourceString("AREI0004"));
	}

	private static void registerServices(Node paramNode) {
		System.out.println(AREResourceManager.getResourceString("AREI0005"));
		Iterator<?> localIterator = paramNode.getChildren("Service").iterator();
		while (localIterator.hasNext()) {
			Node localNode1 = (Node) localIterator.next();
			Attributes localAttributes = localNode1.getAttributes();
			DataElement localDataElement1 = localAttributes.getAttribute("id");
			if ((localDataElement1 == null)
					|| (StringX.isSpace(localDataElement1.getString())))
				System.out.println("--"
						+ AREResourceManager.getResourceString("AREW0004"));
			DataElement localDataElement2 = localAttributes
					.getAttribute("enabled");
			if ((localDataElement2 != null)
					&& (!(localDataElement2.getBoolean())))
				System.out
						.println("--"
								+ MessageFormat.format(AREResourceManager
										.getResourceString("AREW0005"),
										new String[] { localDataElement1
												.getString() }));
			AREServiceStub localAREServiceStub = new AREServiceStub(
					localDataElement1.getString());
			DataElement localDataElement3 = localAttributes
					.getAttribute("initOnStart");
			localAREServiceStub.initOnStart = ((localDataElement3 == null) ? false
					: localDataElement3.getBoolean());
			Node localNode2 = localNode1.getChild("ServiceClass");
			localAREServiceStub.serviceClass = ((localNode2 == null) ? null
					: StringX.trimAll(localNode2.getValue()));
			if (localAREServiceStub.serviceClass == null)
				System.out.println("--"
						+ MessageFormat.format(AREResourceManager
								.getResourceString("AREW0006"),
								new String[] { localAREServiceStub.id }));
			localAREServiceStub.properties.putAll(localNode1.getProperties()
					.getAsProperties(true));
			services.put(localAREServiceStub.id, localAREServiceStub);
			System.out.println("--"
					+ MessageFormat.format(
							AREResourceManager.getResourceString("AREI0007"),
							new String[] { localAREServiceStub.id }));
		}
		System.out.println(AREResourceManager.getResourceString("AREI0006"));
	}

	private static void initStartOnService() {
		System.out.println(AREResourceManager.getResourceString("AREI0008"));
		AREServiceStub localAREServiceStub = null;
		Iterator localIterator = services.values().iterator();
		while (localIterator.hasNext()) {
			localAREServiceStub = (AREServiceStub) localIterator.next();
			if (!(localAREServiceStub.isInitOnStart()))
				continue;
			try {
				localAREServiceStub.loadService();
				localAREServiceStub.initService();
				System.out.println("--"
						+ MessageFormat.format(AREResourceManager
								.getResourceString("AREI0009"),
								new String[] { localAREServiceStub.getId() }));
			} catch (AREException localAREException) {
				getLog().warn(localAREException);
				System.out.println("--"
						+ MessageFormat.format(AREResourceManager
								.getResourceString("AREW0006"),
								new String[] { localAREServiceStub.getId() }));
			}
		}
		System.out.println(AREResourceManager.getResourceString("AREI0010"));
	}

	public static String getConfigureFile() {
		return configureFile;
	}

	public static AREServiceStub getServiceStub(String paramString) {
		AREServiceStub localAREServiceStub = (AREServiceStub) services
				.get(paramString);
		return localAREServiceStub;
	}

	public static int getProperty(String paramString, int paramInt) {
		int i = paramInt;
		String str = systemProperties.getProperty(paramString);
		if (str != null)
			try {
				i = Integer.parseInt(str);
			} catch (Exception localException) {
				i = paramInt;
			}
		return i;
	}

	public static double getProperty(String paramString, double paramDouble) {
		double d = paramDouble;
		String str = systemProperties.getProperty(paramString);
		if (str != null)
			try {
				d = Double.parseDouble(str);
			} catch (Exception localException) {
				d = paramDouble;
			}
		return d;
	}

	public static boolean getProperty(String paramString, boolean paramBoolean) {
		boolean bool = paramBoolean;
		String str = systemProperties.getProperty(paramString);
		if (str != null)
			bool = (str.equalsIgnoreCase("true"))
					|| (str.equalsIgnoreCase("t"))
					|| (str.equalsIgnoreCase("yes"))
					|| (str.equalsIgnoreCase("y")) || (str.equals("1"));
		return bool;
	}

	public static Date getProperty(String paramString, Date paramDate) {
		Date localDate = paramDate;
		String str1 = systemProperties.getProperty(paramString);
		if (str1 != null) {
			if (str1.indexOf(47) > 0)
				str1 = str1.replaceAll("/", "");
			else if (str1.indexOf(45) > 0)
				str1 = str1.replaceAll("-", "");
			String str2 = "yyyyMMdd";
			if (str1.length() == 6)
				str2 = "yyMMdd";
			try {
				localDate = new SimpleDateFormat(str2).parse(str1);
			} catch (ParseException localParseException) {
				localDate = paramDate;
			}
		}
		return localDate;
	}

	public static Date getProperty(String paramString1, Date paramDate,
			String paramString2) {
		Date localDate = paramDate;
		String str = systemProperties.getProperty(paramString1);
		if (str != null) {
			SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat(
					paramString2);
			try {
				localDate = localSimpleDateFormat.parse(str);
			} catch (Exception localException) {
				localDate = paramDate;
			}
		}
		return localDate;
	}

	public static String getProperty(String paramString1, String paramString2) {
		return systemProperties.getProperty(paramString1, paramString2);
	}

	public static String replaceEnvVar(String paramString) {
		return replaceVar(paramString);
	}

	private static String replaceVar(String paramString) {
		Matcher localMatcher = null;
		StringBuffer localStringBuffer = new StringBuffer();
		localMatcher = varPattern.matcher(paramString);
		while (localMatcher.find()) {
			String str = null;
			if (localMatcher.group(1) == null)
				str = System.getProperty(localMatcher.group(2));
			else
				str = getProperty(localMatcher.group(2));
			if (str == null)
				str = "";
			localMatcher.appendReplacement(localStringBuffer, str);
		}
		localMatcher.appendTail(localStringBuffer);
		return localStringBuffer.toString();
	}

	public static String replaceComment(String paramString) {
		String str = "\\{#[^\\}]*\\}";
		return paramString.replaceAll(str, "");
	}

	public static String replaceARETags(String paramString) {
		return replaceEnvVar(replaceComment(paramString));
	}

	public static int getRunMode() {
		return runMode;
	}

	public static void setRunMode(int paramInt) {
		if ((paramInt != 0) && (paramInt != 1) && (paramInt != 3)) {
			System.out.println(new AREException(2, new String[] { String
					.valueOf(paramInt) }).getMessage());
			return;
		}
		runMode = paramInt;
	}

	public static void main(String[] paramArrayOfString) {
	}

	static {
		System.out.println("Amarsoft Runtime Environment, Version " + version);
		System.out
				.println("(C)Copyright 2006-2014 Amarsoft Information & Technology Co., Ltd.. All rights reserved.");
		System.out.println();
		String str1 = System.getProperty("java.version", "1.2");
		String str2 = "1.4.2_12";
		if (str1.compareToIgnoreCase(str2) >= 0) {
		} else {
			System.out
					.println("WARNING: Java version " + str1
							+ " too low to  run ARE, expect " + str2
							+ " or above!!!  ");
		}
	}
}